from PySide6.QtCore import QEvent, QObject
from PySide6.QtGui import QShowEvent, QMouseEvent
from mainUi import *
from recv import *
from network import myHttpRequest
from myqrcode import create_qr_code
from upqiniu import QiniuThread
from mytasks import WaitTasks
import sys, os, time
import threading
import image


class MainWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__()
        # self.setupUi(self)
        # self.resize(400, 300)
        # self.setWindowTitle("YaoDB")
        self.setWindowIcon(QIcon(":icon/logo.png"))
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlags(
            Qt.FramelessWindowHint
            | Qt.Window
            # | QtCore.Qt.WindowStaysOnBottomHint
        )
        # 窗口标记
        self.m_flag = False
        # 第一行
        p = QLabel()
        p.setPixmap(QPixmap(":icon/logo.png").scaled(24, 24))
        t = QLabel("RecVideo ver:1.06")
        t.setStyleSheet("color:white;")
        self.toolbar = QToolBar()
        self.toolbar.setIconSize(QSize(16, 16))
        # self.toolbar.addAction(
        #     QAction(
        #         QApplication.style().standardIcon(QStyle.SP_TitleBarMinButton),
        #         "最小化",
        #         self,
        #     )
        # )
        # self.toolbar.addAction(
        #     QAction(
        #         QApplication.style().standardIcon(QStyle.SP_TitleBarMaxButton),
        #         "最大化",
        #         self,
        #     )
        # )
        self.toolbar.addAction(
            QAction(
                QApplication.style().standardIcon(QStyle.SP_TitleBarCloseButton),
                "关闭",
                self,
            )
        )
        h0 = QHBoxLayout()
        h0.setContentsMargins(0, 0, 0, 0)
        h0.addWidget(p)
        h0.addWidget(t)
        h0.addStretch(1)
        h0.addWidget(self.toolbar)

        self.Xbox = MainChangeWindow()
        # 顶层
        v = QVBoxLayout(self)
        v.setContentsMargins(5, 5, 5, 5)
        v.addLayout(h0)
        v.addWidget(self.Xbox)

        # css
        self.setStyleSheet(
            """
        MainWindow {background-color: qlineargradient(spread:pad, x1:1, y1:0, x2:0, y2:1, stop:0 rgba(14,70,200, 255), stop:1 rgba(255, 255, 255, 255)); border-radius: 5px;}        
        """
        )

        # 系统组件
        self.waitToken = QTimer()
        self.waitToken.timeout.connect(self.MSG_hasWxToken)
        self.network_manager = myHttpRequest()
        self.state = ""
        self.token = ""
        self.userinfo = None
        self.recvwork = WorkerThread()
        self.recvwork.msg.connect(self.MSG_WorkerThread)
        self.recvview = autoRecvVideoViews(self)

        # 信号槽
        self.toolbar.actionTriggered.connect(self.MSG_SYSTEM)

        self.Xbox.page_one.code.installEventFilter(self)

        # 初始化
        self.MSG_hasQrCode()

        # # 测试初始化
        # create_qr_code(
        #     "http://weixin.qq.com/q/02QyjxBHetfMG1h74F1C1C", self.Xbox.page_one.code
        # )
        # QTimer.singleShot(3000, self.installer)

    def installer(self):
        """测试初始化"""
        self.token = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzE4MjkyODExLCJpYXQiOjE3MTgyNDk2MTEsImp0aSI6Ijk5OWRlMThiMGRiNDRlMDlhNzhjZWFjYTZhZmE4OWIzIiwidXNlcl9pZCI6Mn0.uQap7S8q7rnnpGkRzKVzNpT4oIIpy67Oh6FCQtbi8fA"
        # fn = "aaaa.avi"
        fn = "tmp/bbbb.avi"
        # self.Xbox.setCurrentIndex(1)
        # self.MSG_hasWxUserInfo()
        # self.Xbox.page_two.load(self.userinfo)
        self.recvview.show()
        self.hide()
        # self.recvview.MSG_recving(fn)

    def MSG_SYSTEM(self, e):
        """系统工具栏消息"""
        if e.text() == "最小化":
            self.showMinimized()
        if e.text() == "最大化":
            if self.isMaximized():
                self.showNormal()
                e.setIcon(
                    QApplication.style().standardIcon(QStyle.SP_TitleBarMaxButton)
                )
            else:
                self.showMaximized()
                e.setIcon(
                    QApplication.style().standardIcon(QStyle.SP_TitleBarNormalButton)
                )
        if e.text() == "关闭":
            self.close()

    def mousePressEvent(self, QMouseEvent):
        if QMouseEvent.button() == Qt.LeftButton:
            if self.isMaximized():
                return
            pos = QMouseEvent.globalPosition().toPoint()
            self.m_flag = True
            self.m_Position = pos - self.pos()  # 获取鼠标相对窗口的位置
            QMouseEvent.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, QMouseEvent):
        if QMouseEvent.buttons() == Qt.LeftButton and self.m_flag:
            if self.isMaximized():
                self.showNormal()
            pos = QMouseEvent.globalPosition().toPoint()
            self.move(pos - self.m_Position)  # 更改窗口位置
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QCursor(Qt.ArrowCursor))

    def paintEvent(self, event: QPaintEvent) -> None:
        opt = QStyleOption()
        opt.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, p, self)
        return super().paintEvent(event)

    def showEvent(self, event: QShowEvent) -> None:
        # print(event)
        return super().showEvent(event)

    def eventFilter(self, watched: QObject, event: QEvent) -> bool:
        """自己定义事件过滤器"""
        if event.type() == QEvent.MouseButtonPress:
            print(watched)
            if watched == self.Xbox.page_one.code:
                self.MSG_hasQrCode()
                return True
        return super().eventFilter(watched, event)

    def has_chocode(self, len=3, level=0):
        """返回随机数"""
        import random, string

        chars = string.digits
        if level > 0:
            chars += string.ascii_letters
        if level > 1:
            chars += string.punctuation
        return "".join(random.choice(chars) for _ in range(len))

    def MSG_hasQrCode(self):
        """刷新二维码"""
        # r = self.network_manager.hasQrCode()
        # print(f"请求登录二维码 {r}")
        # if r and r.get("rescode") == 200:
        #     self.state = r.get("code")
        #     create_qr_code(r.get("resmsg"), self.Xbox.page_one.code)
        #     if not self.waitToken.isActive():
        #         self.waitToken.start(3000)
        # else:
        #     QMessageBox.warning(self, "警告", "获取二维码失败，请点击刷新！")

        self.state = self.has_chocode(6)
        url = f"http://h5.3vppt.com/#/XRlease/videoDownloaderBridge?state={self.state}"
        create_qr_code(url, self.Xbox.page_one.code)
        if not self.waitToken.isActive():
            self.waitToken.start(3000)

    def MSG_hasWxToken(self):
        """检测登录Token"""
        r = self.network_manager.hasWxToken(self.state)
        print(f"检查用户token {r}")
        if r and r.get("rescode") == 200:
            self.waitToken.stop()
            self.token = r.get("resmsg")
            # self.MSG_hasWxUserInfo()
            self.recvview.show()
            self.recvview.waitTasks.setToken(self.token)
            self.recvview.waitTasks.start()
            self.hide()

    def MSG_hasWxUserInfo(self):
        """获取用户信息"""
        r = self.network_manager.hasWxUserInfo(self.token)
        print(r)
        if r and r.get("rescode") == 200:
            self.userinfo = r.get("resmsg")
            self.Xbox.setCurrentIndex(1)
            self.Xbox.page_two.load(self.userinfo)
        else:
            self.userinfo = None

    def MSG_WorkerThread(self, msg, file):
        """工作线程消息回调"""
        print(msg, file)
        if msg == "over":
            self.Xbox.page_two.model.recv.setText("录屏")
            self.Xbox.page_two.model.recv.setIcon(QIcon("rec.png"))
            """上传文件"""

    def MSG_recvManager(self, act):
        """录屏管理器"""
        if act:
            self.recvwork.start()
        else:
            self.recvwork.stop()

    def MSG_change_page(self, e):
        """主菜单动作按钮"""
        print(e)
        if e.text() == "远程" and e.isChecked() == True:
            self.Xbox.page_two.model.local.setChecked(False)
            self.Xbox.page_two.panel.setCurrentIndex(0)
            return
        if e.text() == "本地" and e.isChecked() == True:
            self.Xbox.page_two.model.remote.setChecked(False)
            self.Xbox.page_two.panel.setCurrentIndex(1)
            return
        if e.text() == "录屏":
            e.setText("停止")
            e.setIcon(QIcon("stop.png"))
            self.MSG_recvManager(True)
            return
        if e.text() == "停止":
            e.setText("录屏")
            e.setIcon(QIcon("rec.png"))
            self.MSG_recvManager(False)
            return

    print(time.time())


# ===========================================================
class autoRecvVideoViews(QDialog):
    """自动接收视频"""

    def __init__(self, parent=None):
        super(autoRecvVideoViews, self).__init__(parent)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setStyleSheet(
            "autoRecvVideoViews {background-color: rgba(5, 5, 5, 200); border-radius: 10px;}"
        )
        # 首行
        self.act_but = QPushButton()
        self.act_but.setIcon(
            QApplication.style().standardIcon(QStyle.SP_DialogNoButton)
        )
        self.act_but.setToolTip("录屏")
        # self.act_but.setStyleSheet(
        #     "max-width: 48px;max-height: 48px;min-width: 48px;min-height: 48px; border-radius: 24px;"
        # )
        self.ste_lab = QLabel("Ready")
        self.ste_lab.setStyleSheet(
            "background-color: rgba(0, 0, 0, 1); color:rgba(201, 201, 201, 1);"
        )

        self.num_lab = QLCDNumber()
        self.num_lab.setDigitCount(3)
        self.num_lab.setMode(QLCDNumber.Dec)
        self.num_lab.setSegmentStyle(QLCDNumber.Flat)
        self.num_lab.setStyleSheet(
            "background-color: rgba(0, 0, 0,1); color:rgba(0,255,0,1);"
        )
        self.num_lab.setProperty("intValue", 3)

        self.out_but = QPushButton()
        self.out_but.setIcon(
            QApplication.style().standardIcon(QStyle.SP_TitleBarCloseButton)
        )
        self.out_but.setToolTip("退出")

        h0 = QHBoxLayout()
        h0.setContentsMargins(0, 0, 0, 0)
        h0.addWidget(self.ste_lab)
        h0.addWidget(self.num_lab)
        # h0.addWidget(self.act_but)
        h0.addWidget(self.out_but)
        # 次行
        self.prog = QProgressBar()
        self.prog.setRange(0, 120)
        self.prog.setTextVisible(False)
        self.prog.setFixedHeight(2)
        self.prog.setStyleSheet("height: 2px;border-radius:1px;")
        h1 = QHBoxLayout()
        h1.setContentsMargins(0, 0, 0, 0)
        h1.addWidget(self.prog)
        # 顶层
        v = QVBoxLayout(self)
        v.setContentsMargins(20, 20, 20, 20)
        v.addLayout(h0)
        # v.addLayout(h1)

        self.setWindowFlags(
            Qt.FramelessWindowHint | Qt.Window | Qt.WindowStaysOnTopHint
        )
        self.move(0, 0)
        self.lang = 120  # 录像时长
        self.iswork = False  # 工作状态
        self.recvwork = WorkerThread()  # 录制线程
        self.recvwork.setLang(self.lang)
        self.recvwork.msg.connect(self.MSG_recving_over)
        self.recvwork.plan.connect(self.MSG_recving_count)
        self.recvwork.state.connect(self.MSG_recving_state)
        self.network_manager = myHttpRequest()  # 网络请求
        self.qiniu_upload = QiniuThread()  # 七牛上传
        self.qiniu_upload.trigger.connect(self.MSG_upQiniu_count)
        self.qiniu_upload.speed.connect(self.MSG_upQiniu_speed)
        self.waitTasks = WaitTasks()  # 远程任务
        self.waitTasks.trigger.connect(self.MSG_hasWxTasks)
        self.out_but.hide()

        self.prog.setRange(0, self.lang)

        # 信号
        self.out_but.clicked.connect(self.logout)
        self.act_but.clicked.connect(self.rec_clicked)

        self.enterEvent = self.mouseEnterEvent
        self.leaveEvent = self.mouseLeaveEvent

    def mouseEnterEvent(self, event: QMouseEvent) -> None:
        self.out_but.show()

    def mouseLeaveEvent(self, event: QMouseEvent) -> None:
        self.out_but.hide()

    def paintEvent(self, event: QPaintEvent) -> None:
        opt = QStyleOption()
        opt.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, p, self)
        return super().paintEvent(event)

    def logout(self):
        """注销"""
        # self.parent().close()
        ask = QMessageBox.question(
            self.parent(),
            "关闭",
            "是否要结束程序",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No,
        )
        if ask == QMessageBox.Yes:
            QApplication.quit()

    def rec_clicked(self):
        """手动按钮动作"""
        if self.act_but.toolTip() == "录屏":
            self.ready_start()
        else:
            self.ready_stop()

    def ready_stop(self):
        """停止录制"""
        self.recvwork.stop()
        self.iswork = False
        self.act_but.setIcon(
            QApplication.style().standardIcon(QStyle.SP_DialogNoButton)
        )
        self.act_but.setToolTip("录屏")
        self.ste_lab.setText("Ready")

    def ready_start(self):
        """开始录制"""
        self.iswork = True
        self.act_but.setIcon(QApplication.style().standardIcon(QStyle.SP_MediaStop))
        self.act_but.setToolTip("停止")
        self.ste_lab.setText("Rec")
        self.num_lab.setProperty("intValue", 4)
        self.ready_recv()

    # def ready_runing(self):
    #     """录制中"""
    #     n = self.num_lab.intValue()
    #     if n > 0:
    #         self.num_lab.setProperty("intValue", n - 1)
    #         QTimer.singleShot(1000, self.ready_runing)
    #     else:
    #         self.ready_stop()

    def ready_recv(self):
        """准备录制"""
        n = self.num_lab.intValue()
        if n > 0:
            self.num_lab.setProperty("intValue", n - 1)
            QTimer.singleShot(1000, self.ready_recv)
        else:
            self.recvwork.start()

    def MSG_upQiniu_speed(self, e):
        """上传七牛云进度回调值"""
        self.prog.setValue(e)
        self.num_lab.setProperty("intValue", e)

    def MSG_upQiniu_count(self, e):
        """上传七牛云完成回调"""
        # print("七牛上传回调", e)
        # self.prog.setRange(0, self.lang)
        self.ste_lab.setText("Ready")
        x = self.network_manager.hasQiniuMysql(self.parent().token, e.get("key"))
        print("本地列表保存", x)
        if x:
            # ccc = QMessageBox.information(self.parent(), "上传成功", "视频剪辑上传成功")
            QApplication.quit()

    def MSG_recving_over(self, e):
        """录制完成回调开始上传"""
        print("录制文件名:", e)
        x = self.network_manager.hasQiniuToken(self.parent().token)
        if not x:
            return

        self.qiniu_upload.setToken(x.get("uptoken"))
        self.qiniu_upload.setFile("./" + e)
        self.qiniu_upload.start()

        self.prog.setRange(0, 100)
        self.ste_lab.setText("Upload")
        print(f"线程启动 {self.qiniu_upload}")

    def MSG_recving_count(self, e):
        """录制进度回调"""
        if e < 0:
            return
        self.num_lab.setProperty("intValue", e)
        self.prog.setValue(e)

    def MSG_recving_state(self, e):
        """录制状态回调"""
        self.ste_lab.setText(e)
        # if e == "over":
        #     self.iswork = False
        #     self.act_but.setIcon(
        #         QApplication.style().standardIcon(QStyle.SP_DialogNoButton)
        #     )
        #     self.act_but.setToolTip("录屏")
        # if e == "start":
        #     self.iswork = True
        #     self.act_but.setIcon(QApplication.style().standardIcon(QStyle.SP_MediaStop))
        #     self.act_but.setToolTip("停止")
        #     self.ste_lab.setText("Rec")
        #     # self.num_lab.setProperty("intValue", self.lang)
        #     # self.ready_runing()
        # if e == "zip":
        #     self.ste_lab.setText("Zip")

    def MSG_hasWxTasks(self, e):
        """获取微信远程任务"""
        print("远程任务", e)
        if e[1] == "stop" and self.act_but.toolTip() == "停止":
            self.ready_stop()
        if e[1] == "start" and self.act_but.toolTip() == "录屏":
            self.ready_start()
        if e[1] == "exit":
            QApplication.quit()


if __name__ == "__main__":
    print("Hello World")
    if not os.path.exists("./tmp"):
        os.mkdir("./tmp")
    app = QApplication(sys.argv)
    mainwindow = MainWindow()
    mainwindow.setWindowTitle("YaoDB")
    # mainwindow.setGeometry(100, 100, 320, 600)
    mainwindow.show()
    sys.exit(app.exec())
